package com.yhq.service;

import com.yhq.dao.SysGeneratorDao;
import com.yhq.utils.GenUtils;
import com.yhq.vo.TableVo;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 * 
 * @author yhq
 * @email sunlightcs@gmail.com
 * @date 2016年12月19日 下午3:33:38
 */
@Service
public class SysGeneratorService {
	@Autowired
	private SysGeneratorDao sysGeneratorDao;

	public List<TableVo> queryList(Map<String, Object> map) {
		System.out.println(map.toString());
		return sysGeneratorDao.queryList(map);
	}

	public int queryTotal(Map<String, Object> map) {
		return sysGeneratorDao.queryTotal(map);
	}

	public Map<String, String> queryTable(String tableName) {
		Map<String, String> map= sysGeneratorDao.queryTable(tableName);
		if(map != null){
			map.put("engine",map.get("ENGINE"));
			map.put("tableName",map.get("TABLENAME"));
			map.put("tableComment",map.get("TABLECOMMENT"));
			map.put("createTime",map.get("CREATETIME"));
		}
		return map;
	}

	public List<Map<String, String>> queryColumns(String tableName) {
		List<Map<String, String>> list = sysGeneratorDao.queryColumns(tableName);
		List<Map<String, String>> newList = new ArrayList<>();
		for (Map<String, String> map:list){
			if(map != null){
				map.put("columnName",map.get("COLUMNNAME"));
				map.put("dataType",map.get("DATATYPE"));
				map.put("columnComment",map.get("COLUMNCOMMENT"));
				map.put("columnKey",map.get("COLUMNKEY"));
				map.put("extra","");
				map.put("dataPrecision",map.get("DATAPRECISION"));
				map.put("dataLength",map.get("DATALENGTH"));
			}
			newList.add(map);
		}
		return newList;
	}

	public byte[] generatorCode(String[] tableNames) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);

		for(String tableName : tableNames){
			//查询表信息
			Map<String, String> table = queryTable(tableName);
			//查询列信息
			List<Map<String, String>> columns = queryColumns(tableName);
			//查询主键
			String pKColumn = sysGeneratorDao.getPK(table.get("tableName" ));
			//生成代码
			GenUtils.generatorCode(table, columns,pKColumn,zip);
		}
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();
	}
}
